package org.dkakunsi.aplikasitoko.form.admin;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.view.JRViewer;

import org.dkakunsi.aplikasitoko.data.entity.Kasir;
import org.dkakunsi.aplikasitoko.data.util.ApplicationDataException;
import org.dkakunsi.aplikasitoko.service.DataService;
import org.dkakunsi.aplikasitoko.service.ReportService;

public class Laporan extends JInternalFrame implements ActionListener {

	private static final long serialVersionUID = 1L;

	private JPanel pnlReport;
	private JButton btnOK;
	private JButton btnKeluar;
	private JTextField textFieldKodeKasir;
	private DataService ds;

	public Laporan() {
		super();
		getContentPane().setLayout(null);
		setBounds(100, 100, 800, 600);
		
		textFieldKodeKasir = new JTextField();
		textFieldKodeKasir.setBounds(10, 12, 110, 25);
		getContentPane().add(textFieldKodeKasir);

		btnOK = new JButton("OK");
		btnOK.setBounds(130, 12, 100, 25);
		getContentPane().add(btnOK);
		btnOK.setActionCommand("OK");
		btnOK.addActionListener(this);
		
		btnKeluar = new JButton("KELUAR");
		btnKeluar.setBounds(240, 12, 100, 25);
		getContentPane().add(btnKeluar);
		btnKeluar.setActionCommand("KELUAR");
		btnKeluar.addActionListener(this);

		pnlReport = new JPanel();
		pnlReport.setBounds(10, 50, 770, 500);
		pnlReport.setLayout(new BorderLayout(0, 0));
		getContentPane().add(pnlReport);
		
		ds = new DataService();
	}

	private void initReport(Kasir kasir) {
		/* method ini tunggu struk yang baru sebagai cetakan dari data backup */
		JasperPrint print = ReportService.getReport(kasir);
		JRViewer viewer = new JRViewer(print);
		pnlReport.removeAll();
		pnlReport.add(viewer,BorderLayout.CENTER);
		pnlReport.updateUI();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String cmd = e.getActionCommand();
		
		if( cmd.equals( "OK" ) ) {
			String idKasir = textFieldKodeKasir.getText();
			Kasir kasir = null;
			try {
				kasir = (Kasir) ds.getInstance(idKasir, "KASIR");
				initReport(kasir);
			} catch (ApplicationDataException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (NullPointerException e1) {
				//JOptionPane.showMessageDialog(this, "Tidak terdapat Laporan", "Laporan", JOptionPane.INFORMATION_MESSAGE);
				e1.printStackTrace();
			}
		} else if( cmd.equals( "KELUAR" ) ) {
			dispose();
		}
		
	}

}
